<?php

namespace App\Library\Redis;

use App\Kuafu\Common\Service\CommonService;
use App\Library\TencentMap\BaseLibrary;
use Closure;
use Illuminate\Redis\Connections\PhpRedisConnection;

class RedisHelp extends BaseLibrary
{

    /**
     * @var PhpRedisConnection
     */
    private PhpRedisConnection $redisConnection;

    public function init()
    {
        $connectionName        = empty($this->config['connectionName']) ? 'default' : $this->config['connectionName'];
        $this->redisConnection = CommonService::getRedis($connectionName);
    }

    /**
     * @return PhpRedisConnection
     */
    public function getRedisInstance(): PhpRedisConnection
    {
        return $this->redisConnection;
    }

    /**
     * @param string $key
     * @param string|Closure $value
     * @param int|null $ttl
     * @return bool
     */
    public function set(string $key, $value = '', int $ttl = null): bool
    {
        return $this->redisConnection->setex($key, $ttl, $value instanceof Closure ? $value() : $value);
    }

    /**
     * @param string $key
     * @param int $ttl
     * @param string|Closure $value
     * @param Closure|null $closure
     * @return mixed|string|null
     */
    public function remember(string $key, int $ttl, $value = '', Closure $closure = null)
    {
        if (($data = $this->get($key, $closure)) == null) {
            $this->set($key, $value, $ttl);
            $data = $this->get($key, $closure);
        }
        return $data;
    }

    /**
     * @param string $key
     * @param Closure|null $closure
     * @return mixed|string|null
     */
    public function get(string $key, Closure $closure = null)
    {
        $value = $this->redisConnection->get($key);
        if ($value != null) {
            if ($closure instanceof Closure) {
                return $closure($value);
            }
        }
        return $value;
    }

    /**
     * @param string|array $key
     * @return int
     */
    public function remove($key): int
    {
        return $this->redisConnection->del($key);
    }
}